package com.tarena.lbs.attach.service.impl;

import com.tarena.lbs.attach.config.MinioConfig;
import com.tarena.lbs.attach.dao.repository.AttachRepository;
import com.tarena.lbs.attach.service.AttachService;
import io.minio.*;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

@Service
public class AttachServiceImpl implements AttachService {
    @Autowired
    private MinioClient minioClient;
    @Autowired
    private MinioConfig minioConfig;
    @Autowired
    private AttachRepository attachRepository;

    private String createBucketPolicyConfig(String bucketName) {
        return """
                {
                  "Statement" : [ {
                    "Action" : "s3:GetObject",
                    "Effect" : "Allow",
                    "Principal" : "*",
                    "Resource" : "arn:aws:s3:::%s/*"
                  } ],
                  "Version" : "2012-10-17"
                }
                """.formatted(bucketName);
    }

    @Override
    @Transactional
    public Integer upload(MultipartFile file, String uuid) throws Exception {
        Integer fieldId;

//        判断文件是否为空
        if (file.isEmpty()) {
            throw new IllegalArgumentException("上传的文件不能为空");
        }
        fieldId = attachRepository.imageAttach(uuid);

//        minio存储桶名
        String bucketName = minioConfig.getBucketName();

//        判断桶是否存在
        boolean bucketExists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
//        桶不存在则创建
        if (!bucketExists) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(bucketName).config(createBucketPolicyConfig(bucketName)).build());
        }

//        上传文件到minio
        minioClient.putObject(PutObjectArgs.builder()
                .bucket(bucketName)
                .object(uuid)
                .stream(file.getInputStream(), file.getSize(), -1)
                .contentType(file.getContentType())
                .build());

        return fieldId;
    }
}
